#include "Util.h"
#include <algorithm>
#include <sstream>
#ifdef _WINDOWS
#include <objbase.h>
#include <strsafe.h>

#else
#include <uuid/uuid.h>
#endif

using namespace renderengine;
using namespace std;
unsigned long Util::getAddress(void* p) {
    return (unsigned long)p;
}

std::string Util::toLower(const std::string& str) {
    std::string lower = str;
    std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
    return lower;
}

std::string Util::toUpper(const std::string& str) {
    std::string upper = str;
    std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
    return upper;
}

std::string Util::createUUID(long long defaultId) {
#ifdef f_WINDOWS
    GUID guid;
    CoCreateGuid(&guid);
    char buf[64] = { 0 };

    _snprintf_s(buf,
        sizeof(buf),
        "%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",
        guid.Data1, guid.Data2, guid.Data3,
        guid.Data4[0], guid.Data4[1],
        guid.Data4[2], guid.Data4[3],
        guid.Data4[4], guid.Data4[5],
        guid.Data4[6], guid.Data4[7]);

    return std::string(buf);
#else
    char buf[64] = { 0 };
    for (int i = 0; i < 20; i++)
    {
        buf[i] = (char)((defaultId % (int)pow(10, 20 - i) / (int)pow(10, 19 - i)) & 0xffff) + 48; // *((char*)&defaultId + i) + 48;
    }
    const char *name = "daxiang";
    for (int i = 20; i < 28; i++)
    {
        buf[i] = name[i - 20];
    }
    return std::string(buf);

#endif
}

#ifdef _WINDOWS

std::string Util::toUtf8(const std::wstring& utf16)
{
    if (utf16.empty())
        return string();

    int length = WideCharToMultiByte(CP_UTF8, 0, utf16.c_str(), -1, NULL, 0, NULL, FALSE);

    string utf8(length, '\0');

    WideCharToMultiByte(CP_UTF8, 0, utf16.c_str(), -1, &utf8[0], length, NULL, FALSE);

    while (utf8[utf8.size() - 1] == '\0')
        utf8.erase(utf8.size() - 1);

    return utf8;
}

std::wstring Util::toUtf16(const std::string& utf8)
{
    if (utf8.empty())
        return wstring();

    int length = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);

    wstring utf16(length, L'\0');

    MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &utf16[0], length);

    while (utf16[utf16.size() - 1] == L'\0')
        utf16.erase(utf16.size() - 1);

    return utf16;
}

#endif

